﻿namespace wToggle.Platform
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;

    using wToggle.Platform.Data;
    using wToggle.Platform.Interfaces;

    using XPlatUtils;

    public class WorkspaceProvider : IWorkspaceProvider
    {
        public async Task<ICollection<Workspace>> GetWorkspaces()
        {
            var cached = CacheLayer.LoadEntities<Workspace>();

            if (cached != null)
            {
                return cached.Any() ? cached : null;
            }

            var auth = ServiceContainer.Resolve<ITogglAuth>();

            try
            {
                using (var client = auth.GetPreauthenticatedClient())
                {
                    var workspaces = await client.GetJsonAsync<List<Workspace>>("workspaces");
                    var result = workspaces ?? new List<Workspace>();

                    await CacheLayer.StoreEntities(workspaces);

                    return result;
                }
            }
            catch (InvalidOperationException e)
            {
                return new List<Workspace>();
            }
        }

        public async Task<Workspace> GetWorkspace(ulong id)
        {
            if (id <= 0)
            {
                throw new ArgumentException("Time workspace ID out of range");
            }

            var cached = CacheLayer.LoadEntity<Workspace>(id);

            if (cached != null)
            {
                return cached;
            }

            var auth = ServiceContainer.Resolve<ITogglAuth>();

            try
            {
                using (var client = auth.GetPreauthenticatedClient())
                {
                    var result = await client.GetJsonAsync<ResponseData<Workspace>>("workspaces/" + id);

                    if (result == null)
                    {
                        return null;
                    }

                    await CacheLayer.StoreEntity(result.Data);

                    return result.Data;
                }
            }
            catch (InvalidOperationException e)
            {
                return null;
            }
        }

        public Task<Workspace> Create(Workspace entity, bool withLock = true)
        {
            throw new NotImplementedException();
        }

        public Task<Workspace> Update(Workspace entry, bool withLock = true)
        {
            throw new NotImplementedException();
        }

        public Task<bool> Delete(ulong id, bool withLock = true)
        {
            throw new NotImplementedException();
        }
    }
}